//
//  ByBonusOptimizeVC.m
//  caipiao_ios
//
//  Created by mc on 2018/9/5.
//  Copyright © 2018年 ZhangZhanbin. All rights reserved.
//

#import "ByBonusOptimizeVC.h"
#import "ByBonusOptimizeHeadView.h"
#import "ByBonusOptimizeSwitchView.h"
#import "ByDocumentaryFourValue.h"
#import "ByBonusAddMinusView.h"
#import "ByBonusOptimizeDetailCell.h"
#import "ByFootBallListBottomView.h"


@interface ByBonusOptimizeVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, assign) NSInteger index;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) ByBonusOptimizeHeadView *handelView;

@property (nonatomic, strong) UIView *bottomBackView;

@property (nonatomic, strong) NSMutableArray *stateArray;

@property (nonatomic, strong) NSMutableArray *bonusArray;

@property (nonatomic, strong) NSMutableArray *selectValueArray;

@property (nonatomic, strong) ByNetModel *orderModel;

@property (nonatomic, strong) ByPayBombView *payBombView;


@end

@implementation ByBonusOptimizeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _index = 0; // 默认值
    
    [self addLeftBackBarButtonItem];
    self.title = @"奖金优化";
    
    [self initViews];
    
    self.handelView.countLabel.text = [NSString stringWithFormat:@"%ld", self.netModel.count * 2 + 2];

    [self loadData];
    [self.view addSubview:self.bottomBackView];
}




- (NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _dataArray;
}

- (NSMutableArray *)stateArray{
    if (_stateArray == nil) {
        _stateArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _stateArray;
}

- (NSMutableArray *)bonusArray {
    if (_bonusArray == nil) {
        _bonusArray = [NSMutableArray array];
    }
    return _bonusArray;
}


- (void)loadData{
    ByNetModel *netModel = [[ByNetModel alloc] init];
    netModel.numDic = self.netModel.numDic;
    netModel.multiple = self.netModel.multiple;
    netModel.free_pass = self.netModel.free_pass;
    
    [ByCoreToolAlert showLoadind:@"投注处理中" hasMasker:YES];
    [ByBallApi footballVerify:netModel success:^(ByNetBaseResult *result) {
        
        [ByCoreToolAlert hideHud];
        SLog(@"足球校验 = %@", result.data);
        NSDictionary *dictionary = result.data[@"data"];
        
        [self.dataArray removeAllObjects];
        [self.stateArray removeAllObjects];
        for (NSDictionary *dic in dictionary[@"list"]) {
            ByNetModel *netModel = [[ByNetModel alloc] initContentWithDic:dic];
            [self handleModel:netModel WithDic:dic];
            [self.dataArray addObject:netModel];
            [self.stateArray addObject:@0];
        }
        
        
        for (ByNetModel *netModel in self.dataArray) {
            [self.bonusArray addObject:[NSString stringWithFormat:@"%.2f",netModel.bonus.floatValue]];
        }
        
        [self loadComputingSchemeData];
        
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}

- (void)loadComputingSchemeData {
    
    NSString *typestr = @"";
    if (_index == 0) {
        typestr = @"avg";
    }
    if (_index == 1) {
        typestr = @"hot";
    }
    if (_index == 2) {
        typestr = @"cold";
    }
    
    
    NSDictionary *parameters = @{
                                 @"type":typestr,
                                 @"cost":self.handelView.countLabel.text,
                                 @"bonus":[ByBallApi toJSONData:self.bonusArray],
                                 };
    if (parameters == nil || parameters == NULL)return;
    NSLog(@"parameters = %@", parameters);
    [ByCoreToolAlert showLoadind:@"加载中" hasMasker:YES];
    [ByBallApi BasketBallComputingSchemeData:parameters success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert hideHud];
        self.selectValueArray = [NSMutableArray array];
        SLog(@"奖金优化 = %@", result.data);
        if ([result.data isKindOfClass:[NSNull class]]) {
            return;
        }
        NSArray *dataArray = result.data[@"data"];
        
        if ([dataArray isKindOfClass:[NSNull class]]) {
            return;
        }
        for (NSArray *array in dataArray) {
            NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
            [dataDic setObject:[NSString stringWithFormat:@"%.2f",[array[0] floatValue]] forKey:@"bonus"];
            [dataDic setObject:array[1] forKey:@"multiple"];
            [self.selectValueArray addObject:dataDic];
        }
        
        [self.tableView reloadData];

    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}


- (void)handleModel:(ByNetModel *)netModel1  WithDic:(NSDictionary *)dic{
    NSArray *array = [netModel1.content componentsSeparatedByString:@"|"];
    netModel1.count = array.count;
    NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:1];
    
    for (NSString *string in array) {
        
        NSArray *contentArray = [string componentsSeparatedByString:@"-"];
        NSString *timeString = [contentArray firstObject];
        NSString *play_type = [contentArray objectAtIndex:1];
        NSString *valueString = [contentArray objectAtIndex:2];
        NSLog(@"timeString =%@,play_type = %@", timeString,play_type);
        for (ByNetModel *netModel in self.selectedArray) {
            NSString *key = [NSString stringWithFormat:@"%@%@",netModel.netModel.timeString,netModel.netModel.num_type];
            key =  [key stringByReplacingOccurrencesOfString:@"-" withString:@""];
            if ([timeString isEqualToString:key]) {
                
                //胜平负
                if ([play_type isEqualToString:@"3010"]) {
                    
                    for (ByNetModel *valueModel in netModel.selectedSpfArray) {
                        if ([valueModel.numKey isEqualToString:valueString]) {
                            valueModel.h_cn_abbr = netModel.netModel.h_cn_abbr;
                            valueModel.a_cn_abbr = netModel.netModel.a_cn_abbr;
                            valueModel.num = netModel.netModel.num;
                            [tempArray addObject:valueModel];
                            continue;
                        }
                    }
                    
                //让球胜平负
                }else if ([play_type isEqualToString:@"3006"]){
                    
                    for (ByNetModel *valueModel in netModel.selectedRSpfArray) {
                        if ([valueModel.numKey isEqualToString:valueString]) {
                            valueModel.h_cn_abbr = netModel.netModel.h_cn_abbr;
                            valueModel.a_cn_abbr = netModel.netModel.a_cn_abbr;
                            valueModel.num = netModel.netModel.num;
                            [tempArray addObject:valueModel];
                            continue;
                        }
                    }
                    
                 //半全场胜负
                }else if ([play_type isEqualToString:@"3009"]){
                    
                    for (ByNetModel *valueModel in netModel.selectedHalfAllArray) {
                        if ([valueModel.numKey isEqualToString:valueString]) {
                            valueModel.h_cn_abbr = netModel.netModel.h_cn_abbr;
                            valueModel.a_cn_abbr = netModel.netModel.a_cn_abbr;
                            valueModel.num = netModel.netModel.num;
                            [tempArray addObject:valueModel];
                            continue;
                        }
                    }
                    
                 //全场比分
                }else if ([play_type isEqualToString:@"3007"]){
                    
                    for (ByNetModel *valueModel in netModel.selectedScoresArray) {
                        if ([valueModel.numKey isEqualToString:valueString]) {
                            valueModel.h_cn_abbr = netModel.netModel.h_cn_abbr;
                            valueModel.a_cn_abbr = netModel.netModel.a_cn_abbr;
                            valueModel.num = netModel.netModel.num;
                            [tempArray addObject:valueModel];
                            continue;
                        }
                    }
                 //总进球
                }else if ([play_type isEqualToString:@"3008"]){
                    for (ByNetModel *valueModel in netModel.selectedGoalsArray) {
                        if ([valueModel.numKey isEqualToString:valueString]) {
                            valueModel.h_cn_abbr = netModel.netModel.h_cn_abbr;
                            valueModel.a_cn_abbr = netModel.netModel.a_cn_abbr;
                            valueModel.num = netModel.netModel.num;
                            [tempArray addObject:valueModel];
                            continue;
                        }
                    }
                    
                    
                }
            }
            
        }
    }
    
    
    netModel1.ball_infoArray = [tempArray copy];
}



- (void)initViews{
    
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 97 + 35)];
    
    ByBonusOptimizeHeadView *handelView = [[ByBonusOptimizeHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 52)];
    [headView addSubview:handelView];
    NSInteger minimum = self.netModel.count  * 2 + 2;
   
    __weak typeof(self) weakSelf = self;
    handelView.minimum = minimum;
    handelView.updateBlock = ^(){
        [weakSelf loadComputingSchemeData];
    };
    
    self.handelView = handelView;
    
    ByBonusOptimizeSwitchView *switchView = [[ByBonusOptimizeSwitchView alloc] initWithFrame:CGRectMake(0, handelView.bottom, SCREEN_WIDTH, 45)];
    [headView addSubview:switchView];
    
    switchView.selectValueBlock = ^(NSInteger index){
        weakSelf.index = index;
        [weakSelf loadComputingSchemeData];
    };
    
    ByDocumentaryFourValue *titleView = [[ByDocumentaryFourValue alloc] initWithFrame:CGRectMake(0, switchView.bottom, SCREEN_WIDTH, 35)];
    [headView addSubview:titleView];
    
    titleView.valueLabel1.text = @"单注明细";
    titleView.valueLabel2.text = @"单倍奖金(元)";
    titleView.valueLabel3.text = @"倍数";
    titleView.valueLabel4.text = @"奖金(元)";
    titleView.line.hidden = NO;
    titleView.bottomLine.hidden = NO;
    titleView.backgroundColor = [UIColor colorWithHexString:@"#FFF8F9"];
    
    for (int i = 1; i < 4; i++) {
        UILabel *line = [[UILabel alloc] init];
        [titleView addSubview:line];
        line.backgroundColor = BY_LINE_COLOR;
        if (i == 1) {
            line.frame = CGRectMake(i * SCREEN_WIDTH / 4.0, 0, 1, 35);
        }else if (i == 2){
            line.frame = CGRectMake(i * SCREEN_WIDTH / 4.0 - 10, 0, 1, 35);
        }else if (i == 3){
            line.frame = CGRectMake(i * SCREEN_WIDTH / 4.0 + 10, 0, 1, 35);
        }
    }
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STATUS_NAV - 60) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = headView;
    
}

- (UIView *)bottomBackView {
    if (_bottomBackView == nil) {
        _bottomBackView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-STATUS_NAV-60, SCREEN_WIDTH, 60)];
        _bottomBackView.backgroundColor = [UIColor whiteColor];
        
        UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sureBtn.backgroundColor = BY_THEME_COLOR;
        [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        sureBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [sureBtn addTarget:self action:@selector(handleSureBtn:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomBackView addSubview:sureBtn];
        [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.right.equalTo(self.bottomBackView).offset(0);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 60));
        }];
        
    }
    return _bottomBackView;
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSNumber *number = [self.stateArray objectAtIndex:section];
    if (number.integerValue == 1) {
        return 2;
    }else{
        return 1;
    }
}

- (NSDictionary *)getDictionaryWithModel:(ByNetModel *)netModel{
    
    for (NSDictionary *dic in self.selectValueArray) {
        NSString *bonus = dic[@"bonus"];
        if (bonus.integerValue - netModel.bonus.integerValue == 0) {
            return dic;
        }
    }
    return [NSDictionary dictionary];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ByNetModel *netModel = [self.dataArray objectAtIndex:indexPath.section];

    NSDictionary *valueDic = [self getDictionaryWithModel:netModel];

    if (indexPath.row == 0) {
        static NSString *cellIdentifier = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        
        for (UIView *view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
        
        ByNetModel *model = [netModel.ball_infoArray firstObject];
        CGFloat width = SCREEN_WIDTH / 4.0;
        CGFloat magin = 10;
        UIControl *control = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, width, 50)];
        [cell.contentView addSubview:control];
        [control addTarget:self action:@selector(controlAction:) forControlEvents:UIControlEventTouchUpInside];
        control.tag = 100 + indexPath.section;
        
        UILabel *titleLabel = [[UILabel alloc] init];
        [control addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(control).offset(0);
            make.right.equalTo(control).offset(0);
            make.bottom.equalTo(control.mas_centerY).offset(0);
            make.height.mas_equalTo(@14);
        }];
        titleLabel.font = FONT(12);
        titleLabel.textColor = [UIColor grayColor];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = model.h_cn_abbr;
        
        UIImageView *iconView = [[UIImageView alloc] init];
        [control addSubview:iconView];
        [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(control).offset(0);
            make.top.equalTo(titleLabel.mas_bottom).offset(5);
            make.size.mas_equalTo(CGSizeMake(12, 8));
        }];
        
        NSNumber *number = [self.stateArray objectAtIndex:indexPath.section];
        if (number.integerValue == 1) {
            iconView.image = [UIImage imageNamed:@"xiala向上"];
        }else{
            iconView.image = [UIImage imageNamed:@"xiala向下"];
        }
        
        UILabel *singleLabel = [[UILabel alloc] initWithFrame:CGRectMake(width, 0, width - magin , 50)];
        [cell.contentView addSubview:singleLabel];
        singleLabel.textColor = [UIColor grayColor];
        singleLabel.font = FONT(12);
        singleLabel.textAlignment = NSTextAlignmentCenter;
        
        UILabel *bonusLabel = [[UILabel alloc] init];
        [cell.contentView addSubview:bonusLabel];
        [bonusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(cell.contentView).offset(0);
            make.top.equalTo(cell.contentView).offset(0);
            make.bottom.equalTo(cell.contentView).offset(0);
            make.width.mas_equalTo(@(width - magin));
        }];
        bonusLabel.textAlignment = NSTextAlignmentCenter;;
        bonusLabel.font = FONT(12);
        bonusLabel.textColor = BY_THEME_COLOR;
        
        
        
        ByBonusAddMinusView *addMinusView = [[ByBonusAddMinusView alloc] init];
        [cell.contentView addSubview:addMinusView];
        [addMinusView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.contentView).offset(0);
            make.bottom.equalTo(cell.contentView).offset(0);
            make.right.equalTo(bonusLabel.mas_left).offset(0);
            make.left.equalTo(singleLabel.mas_right).offset(0);
        }];
        
        //addMinusView.countLabel.enabled = NO;
        __weak typeof(ByBonusAddMinusView *) weakSelfView = addMinusView;
        addMinusView.updateBlock = ^(NSInteger tag) {
            bonusLabel.text = [NSString stringWithFormat:@"%.2f", singleLabel.text.floatValue * addMinusView.countLabel.text.integerValue];
            if (tag == 100) {
                self.handelView.countLabel.text = [NSString stringWithFormat:@"%ld",self.handelView.countLabel.text.integerValue - 2];
            }else {
                self.handelView.countLabel.text = [NSString stringWithFormat:@"%ld",self.handelView.countLabel.text.integerValue + 2];
            }
            
            NSMutableDictionary *dataDic = [self.selectValueArray objectAtIndex:indexPath.section];
            [dataDic setObject:weakSelfView.countLabel.text forKey:@"multiple"];
            [self.selectValueArray addObject:dataDic];
            
        };
        
        if (_index == 0 || _index == 1 || _index == 2) {
            bonusLabel.text = [NSString stringWithFormat:@"%.2f", [valueDic[@"bonus"] floatValue] * [valueDic[@"multiple"] floatValue]];
            
            addMinusView.countLabel.text = [valueDic[@"multiple"] stringValue];
            
            singleLabel.text = [NSString stringWithFormat:@"%.2f", [valueDic[@"bonus"] floatValue]];
        }
        
        

        for (int i = 1; i < 4; i++) {
            UILabel *line = [[UILabel alloc] init];
            [cell.contentView addSubview:line];
            line.backgroundColor = BY_LINE_COLOR;
            if (i == 1) {
                line.frame = CGRectMake(i * SCREEN_WIDTH / 4.0, 0, 1, 50);
            }else if (i == 2){
                line.frame = CGRectMake(i * SCREEN_WIDTH / 4.0 - magin, 0, 1, 50);
            }else if (i == 3){
                line.frame = CGRectMake(i * SCREEN_WIDTH / 4.0 + magin, 0, 1, 50);
            }
        }
        
        
        UILabel *line = [[UILabel alloc] init];
        [cell.contentView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell.contentView).offset(0);
            make.right.equalTo(cell.contentView).offset(0);
            make.bottom.equalTo(cell.contentView).offset(0);
            make.height.mas_equalTo(@1);
        }];
        line.backgroundColor = BY_LINE_COLOR;
        
        return cell;
        
        
    }else{
        
        ByBonusOptimizeDetailCell *cell = [ByBonusOptimizeDetailCell cellWithTableView:tableView];
        cell.netModel = netModel;
        return cell;
        
    }
    
    
    
    
   
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ByNetModel *netModel = [self.dataArray objectAtIndex:indexPath.section];
    if (indexPath.row == 0) {
        return 50;
    }else{
        return 40 + 40 * netModel.count;
    }
}

- (void)controlAction:(UIControl *)control{
    NSInteger section = control.tag-100;
    if([self.stateArray[section] integerValue] == 0){
        [self.stateArray replaceObjectAtIndex:section withObject:@(1)];
    }else{
        
        [self.stateArray replaceObjectAtIndex:section withObject:@(0)];
    }
    
    [self.tableView reloadData];
    
}

- (void)handleSureBtn:(UIButton *)button {
    
    [self bonusOptimize];
}

- (void)bonusOptimize{
    
    
    if (self.dataArray == nil || self.dataArray.count == 0) {
        return;
    }
    if (self.selectValueArray == nil || self.selectValueArray.count == 0) {
        return;
    }
    
    
    
    NSMutableArray *numArray = [NSMutableArray array];
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        ByNetModel *model = self.dataArray[i];
        NSDictionary *valueDic = self.selectValueArray[i];
        NSMutableDictionary *dataNum = [NSMutableDictionary dictionary];
        [dataNum setObject:[NSString stringWithFormat:@"%.2f",model.bonus.floatValue] forKey:@"bonus"];
        [dataNum setObject:model.content forKey:@"content"];
        [dataNum setObject:[NSString stringWithFormat:@"%@",valueDic[@"multiple"] ] forKey:@"multiple"];
        [dataNum setObject:model.pass_type forKey:@"pass_type"];
        [dataNum setObject:model.strung forKey:@"strung"];
        [numArray addObject:dataNum];
    }
    
    ByNetModel *netModel = [[ByNetModel alloc] init];
    netModel.numArray = numArray;
    netModel.multiple = @"1";
    netModel.free_pass = self.netModel.free_pass;
    netModel.origin_numDic = self.netModel.origin_numDic;
    netModel.order_type = @"smart";
    [ByCoreToolAlert showLoadind:@"投注处理中" hasMasker:YES];
    [ByBallApi footballOptimizationCreateOrder:netModel success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert hideHud];
        NSLog(@"足球投注 = %@", result.data);
        self.orderModel = [[ByNetModel alloc] initContentWithDic:result.data[@"data"]];
        self.payBombView.moneyLabel.text = [NSString stringWithFormat:@"%@元", self.orderModel.amount];
        self.payBombView.orderModel = self.orderModel;
        [self.payBombView show];
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showOnlyText:result.msg];
    }];
    
    
}



- (ByPayBombView *)payBombView{
    if (_payBombView == nil) {
        _payBombView = [[ByPayBombView alloc] init];
        
        __weak typeof(self) weakSelf = self;
        _payBombView.sureBlock = ^(){
            [weakSelf.payBombView remove];
            weakSelf.payBombView = nil;
            [weakSelf by_normalPopVC:@""];
        };
        
        _payBombView.otherSureBlock = ^(NSString *str,NSInteger type){
            
            [weakSelf.payBombView remove];
            weakSelf.payBombView = nil;
            
            if (type == 1) {
                ByWebViewController *vc = [[ByWebViewController alloc] initWithTotalUrlString:str];
                vc.titleString = @"支付宝支付";
                [weakSelf by_normalPush:vc hasNavi:YES];
            }else{
                ByWechatPayQrView *vc = [[ByWechatPayQrView alloc] init];
                vc.title = @"微信支付";
                vc.str = str;
                [weakSelf by_normalPush:vc hasNavi:YES];
            }
            
        };
        
        
        _payBombView.selectBlock = ^(NSInteger index){
            
        };
    }
    return _payBombView;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
